package crossrun.tool.pdf2img;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.ClipData;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.nio.charset.StandardCharsets;

import crossrun.tool.pdf2img.util.PdfUtil;
import crossrun.tool.pdf2img.livedata.PdfFileReadData;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;

public class MainActivity extends AppCompatActivity {

    Button btnStart, btnShare;

    TextLogUtil logUtil;
    PdfUtil pdfUtil;
    Uri uri;
    String zipPath;
    File pdfFile;
    final String ERROR_DEFAULT = "获取文件失败，请重新选择文件";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getIntentData();
        initView();
    }

    private void initView() {
        logUtil = new TextLogUtil(findViewById(R.id.scrollView), findViewById(R.id.log));
        btnStart = findViewById(R.id.btnStart);
        btnStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                btnStart.setEnabled(false);
                startPdf();
            }
        });
        btnShare = findViewById(R.id.btnShare);
        btnShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                shareFile();
            }
        });
        pdfUtil = new PdfUtil(this);
        pdfUtil.setListener(listener);
        TextView txt = findViewById(R.id.fileSelected);
        if (uri != null) {
            txt.setText(uri.toString());
            getPdfFile(uri);
        } else {
            txt.setClickable(true);
            txt.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    selectPdfFile();
                }
            });
        }
    }

    public void getIntentData() {
        Intent intent = getIntent();
        uri = intent.getData();
        if (uri == null && intent.getClipData() != null) {
            ClipData.Item item = intent.getClipData().getItemAt(0);
            if (item != null) {
                uri = item.getUri();
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_index, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@androidx.annotation.NonNull MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case R.id.settings:
                startActivity(new Intent(this,SettingsActivity.class));
                break;
            case R.id.fileMana:
                startActivity(new Intent(this,CacheFileActivity.class));
                break;
            default:
        }
        return true;
    }

    private void startPdf() {
        if (pdfFile == null) {
            logUtil.logln(ERROR_DEFAULT);
            btnStart.setEnabled(true);
            return;
        }
        pdfUtil.start(pdfFile);
    }


    PdfUtil.PdfTransListener listener = new PdfUtil.PdfTransListener() {
        @Override
        public void onStart() {
            myHandler.sendEmptyMessage(START);
        }

        @Override
        public void onProcess(int p, String msg) {
            myHandler.obtainMessage(PROCESS, msg).sendToTarget();
        }

        @Override
        public void onSuccess(String zip) {
            myHandler.obtainMessage(SUCCESS, zip).sendToTarget();
        }

        @Override
        public void onFailed(Throwable e) {
            myHandler.obtainMessage(FAILED, e).sendToTarget();
        }
    };

    /**
     * 调用系统文件选择pdf文件
     */
    private void selectPdfFile() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("application/pdf");
        intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, false);//打开多个文件
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        try {
            startActivityForResult(Intent.createChooser(intent, "请选择文件"), 1);
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
            Toast.makeText(this, "请 安装文件管理器", Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 把转换完成的zip文件分享出去
     */
    private void shareFile() {
        if (TextUtils.isEmpty(zipPath)) {
            Toast.makeText(this, "获取压缩文件失败", Toast.LENGTH_SHORT).show();
            logUtil.logln("获取压缩文件失败");
            return;
        }
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        File file = new File(zipPath);
        Uri uri = FileProvider.getUriForFile(this, getPackageName() + ".fileprovider", file);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.setDataAndType(uri, "*/*");
        startActivity(intent);
        logUtil.log(zipPath);
        logUtil.logln("分享结束");
    }

    Dialog dialog;

    private void showWaitDialog() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
        dialog = new AlertDialog.Builder(this)
                .setTitle(R.string.processing)
                .setCancelable(false)
                .setMessage(R.string.processing_file)
                .show();
    }

    private void dismissWaitDialog() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    /**
     * 处理从uri获取file
     *
     * @param uri 文件
     */
    private void getPdfFile(Uri uri) {
        pdfFile = null;
        PdfFileReadData.getPdfFileFromUri(this, uri, observerFile());
    }

    /**
     * 处理file完成的逻辑
     *
     * @return pdf
     */
    private Observer<File> observerFile() {
        return new Observer<File>() {
            @Override
            public void onSubscribe(@NonNull Disposable d) {
                showWaitDialog();
            }

            @Override
            public void onNext(@NonNull File file) {
                pdfFile = file;
                logUtil.log("获取到文件");
                logUtil.logln(pdfFile.getAbsolutePath());
                dismissWaitDialog();
            }

            @Override
            public void onError(@NonNull Throwable e) {
                logUtil.logln(e.toString());
                dismissWaitDialog();
            }

            @Override
            public void onComplete() {

            }
        };
    }

    public static final int START = 0;
    public static final int PROCESS = 1;
    public static final int SUCCESS = 2;
    public static final int FAILED = 3;

    MyHandler myHandler = new MyHandler(this);

    static class MyHandler extends Handler {
        WeakReference<MainActivity> weakReference;

        MyHandler(MainActivity activity) {
            weakReference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            MainActivity activity = weakReference.get();
            if (activity == null) {
                return;
            }
            switch (msg.what) {
                case START:
                    activity.logUtil.log("开始转换");
                    activity.logUtil.logln(new String(activity.uri.toString().getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8));
                    break;
                case PROCESS:
                    activity.logUtil.logln((String) msg.obj);
                    break;
                case SUCCESS:
                    activity.logUtil.log("转换完成");
                    activity.logUtil.log(activity.uri.toString());
                    activity.logUtil.logln("===========================");
                    activity.zipPath = (String) msg.obj;
                    activity.btnStart.setEnabled(true);
                    activity.btnShare.setVisibility(View.VISIBLE);
                    break;
                case FAILED:
                    activity.logUtil.logln(msg.obj.toString());
                    activity.btnStart.setEnabled(true);
                    break;
                default:
            }
        }

        void recycle() {
            weakReference.clear();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == 1) {
            uri = data.getData();
            if (uri == null && data.getClipData() != null) {
                ClipData.Item item = data.getClipData().getItemAt(0);
                if (item != null) {
                    uri = item.getUri();
                }
            }
            getPdfFile(uri);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        logUtil.recycle();
        pdfUtil.recycle();
        myHandler.recycle();
    }
}
